package cn.angleline.cloudhub.easbi.util

import org.apache.commons.codec.binary.Base64
import org.apache.commons.codec.binary.Hex
import org.hibernate.id.UUIDHexGenerator
import org.springframework.beans.factory.annotation.Value
import org.springframework.stereotype.Component
import java.util.*
import javax.crypto.Cipher
import javax.crypto.spec.SecretKeySpec

@Component
class EncryptUtils {
//
//    @Value("\${cloudhub.aes-key}")
//    private lateinit var globalAesKey: String

    private fun getAesSecretKeySpec(aesKey: String): SecretKeySpec {
        val secretKey = SecretKeySpec(aesKey.toByteArray(), "AES").encoded
        return SecretKeySpec(secretKey, "AES")
    }

    /**
     * 加密
     */
    fun aesEncryptData(data: String, aesKey: String): String {
        val cipher = Cipher.getInstance("AES")
        cipher.init(Cipher.ENCRYPT_MODE, getAesSecretKeySpec(aesKey))
        val rawEncryptedData = cipher.doFinal(data.toByteArray())
        return Base64.encodeBase64String(rawEncryptedData)
    }

    /**
     * 解密
     */
    fun aesDecryptData(data: String, aesKey: String): String {
        val cipher = Cipher.getInstance("AES")
        cipher.init(Cipher.DECRYPT_MODE, getAesSecretKeySpec(aesKey))
        val rawDecryptedData = cipher.doFinal(Base64.decodeBase64(data))
        return String(rawDecryptedData)
    }

    fun uuid() = UUIDHexGenerator().generate(null, null) as String
}